package com.eastmelon.tcp;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Administrator 这个服务端有个局限性，当A客户连接上以后，被服务端获取到，服务端执行具体流程，这时候B客户端连接，
 *         只有等待while结束再次执行accept， 服务端最好就是将每个客户端封装到单独的线程当中，这样就可以同时处理多个请求
 *         只要明确了每个客户端要在服务端执行的代码即可，将该代码存入run方法当中
 */
public class PicServer {

	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(10005);
		while (true) {
			Socket s = ss.accept();
			new Thread(new PicThread(s)).start();
		}

		// ss.close();
	}
}

class PicThread implements Runnable {
	private Socket s;
	PicThread(Socket s) {
		this.s = s;
	}

	public void run() {
		try {
			String ip = s.getInetAddress().getHostAddress();
			System.out.println(ip + "...connected");
			InputStream in = s.getInputStream();
			FileOutputStream fos = new FileOutputStream("D:\\love.jpg");
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
			OutputStream out = s.getOutputStream();
			out.write("上传成功".getBytes());
			fos.close();
			s.close();
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

}
